<?php

	$_VIEW = 'modules/user/views/changeProfileView.php';
	
	$profil = fopen('./data/user/'.$_SESSION['connect'].'.txt', 'r');
	$pass = fgets($profil);
	$pass = rtrim($pass);
	$mail = fgets($profil);
	fclose($profil);
	
	
	
	if(isset($_POST['change'])){
	
		if(isset($_POST['lastpw']) and !empty($_POST['lastpw'])){
		
			$last = $_POST['lastpw'];
			
			if(strcmp($last, $pass) != 0){
				
				$error['last'] = 'Ancien mot de passe incorrect';

			}
			else{
				
				if(isset($_POST['newpw']) and !empty($_POST['newpw'])){
					
					if(isset($_POST['cpw']) and !empty($_POST['cpw'])){
							
						if($_POST['newpw'] == $_POST['cpw']){
							
							$pass = $_POST['newpw'];
						
						}
						else{
							$error['matchpw'] = 'Les nouveaux mots de passe doivent correspondre';
						}
					}
					else{
						$error['cpw'] = 'Rentrez la confirmation de nouveau mot de passe';
					}
				}
				else{
					$error['pw'] = 'Rentrez un nouveau mot de passe';
				}
			}
		}
		
		if(isset($_POST['mail']) && !empty($_POST['mail'])){
			if (preg_match("#^[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}$#", $_POST['mail'])){
				$mail = $_POST['mail'];
			} 
			else{
				$error['mail'] = 'Erreur : l\'adresse n\'est pas valide !'; 
			}
		}
		
		if(!isset($error)){
			$profil2 = fopen('./data/user/' . $_SESSION['connect'] . '.txt', 'w+');
			$pass = rtrim($pass);
			fwrite($profil2, $pass . "\n" . $mail);
			fclose($profil2);
			header('Location: index.php?page=user/profile');
		}	 
	}
	
	if(isset($_POST['cancel'])){
		header('Location: index.php?page=user/profile');
	}
			
?>